<template>

  <div class="app-container">

    <h2 style="text-align: center;">发布新课程</h2>

    <el-steps :active="1" process-status="wait" align-center style="margin-bottom: 40px;">
      <el-step title="填写课程基本信息"/>
      <el-step title="创建课程大纲"/>
      <el-step title="最终发布"/>
    </el-steps>

    <el-form label-width="120px">

      <el-form-item label="课程标题">
        <el-input v-model="courseInfo.title" placeholder=" 示例：机器学习项目课：从基础到搭建项目视频课程。专业名称注意大小写"/>
      </el-form-item>

      <!-- 所属分类 TODO -->
      <!--课程分类开始-->
      <el-form-item label="课程分类">
        <el-select v-model="courseInfo.subjectParentId" placeholder="一级分类" @change="changeSubjectParentId">
          <el-option
            v-for="subject in subjectTreeList"
            :key="subject.id"
            :label="subject.title"
            :value="subject.id"/>
        </el-select>
        <el-select v-model="courseInfo.subjectId" placeholder="二级分类">
          <el-option
            v-for="subject in subjectTwoList"
            :key="subject.id"
            :label="subject.title"
            :value="subject.id"/>
        </el-select>
      </el-form-item>
      <!--课程分类结束-->
      <!-- 课程讲师 -->
      <el-form-item label="课程讲师">
        <el-select v-model="courseInfo.teacherId" placeholder="请选择">
          <el-option
            v-for="teacher in teacherList"
            :key="teacher.id"
            :label="teacher.name"
            :value="teacher.id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="总课时">
        <el-input-number :min="0" v-model="courseInfo.lessonNum" controls-position="right" placeholder="请填写课程的总课时数"/>
      </el-form-item>

      <!-- 课程简介开始 -->
      <el-form-item label="课程简介">
        <tinymce :height="300" v-model="courseInfo.description"/>
      </el-form-item>
      <!-- 课程简介结束-->

      <!-- 课程封面开始-->
      <el-form-item label="课程封面">
        <el-upload
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          :action="BASE_API+'/eduOss/uploadFile'"
          accept="image/png,image/jpg,image/jpeg"
          class="avatar-uploader">
          <img :src="courseInfo.cover" style="width: 50%">
        </el-upload>
      </el-form-item>
      <!-- 课程封面结束-->

      <el-form-item label="课程价格">
        <el-input-number :min="0" v-model="courseInfo.price" controls-position="right" placeholder="免费课程请设置为0元"/>
        元
      </el-form-item>

      <el-form-item>
        <el-button :disabled="saveBtnDisabled" type="primary" @click="next">保存并下一步</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import Tinymce from '@/components/Tinymce'
import {addCourseInfo, getCourseInfo, updateCourseInfo} from "@/api/edu/course";
import {getAllTeacher} from "@/api/edu/teacher";
import {getAllSubjectToTree} from "@/api/edu/subject";

export default {
  name: "info",
  components: {Tinymce},
  data() {
    return {
      courseId: '',
      teacherList: [],
      subjectTreeList: [],
      courseInfo: {
        id: '',
        title: '',
        subjectParentId: '',//一级分类id
        subjectId: '',//二级分类id
        teacherId: '',
        lessonNum: 0,
        description: '',
        cover: '/static/moren_fengmian.png',//封面
        price: 0,
      },
      saveBtnDisabled: false, // 保存按钮是否禁用
      BASE_API: process.env.BASE_API, // 接口API地址
      OSS_PATH: process.env.OSS_PATH, // 阿里云OSS地址
      isUpdate: false,
    }
  },
  created() {
    //获取讲师信息
    this.init();
    this.getAllTeacher();
    //获取课程分类信息
    this.getAllSubjectToTree();
  },
  //计算属性
  computed: {
    //二级分类
    subjectTwoList() {
      if (this.courseInfo.subjectParentId) {
        return this.subjectTreeList.filter(item => {
          return item.id === this.courseInfo.subjectParentId;
        })[0].children;
      } else {
        return []
      }
    }
  },
  watch: {
    $route(to, from) {
      this.init();
    },
    courseInfo: {
      handler(val, oldVal) {
        //不是第一次赋值，则不修改
        if (val === oldVal) {
          this.isUpdate = true;
        }
      },
      deep: true
    }
  },
  methods: {
    //页面初始化方法，根据路径判断是添加还是更新
    init() {
      //获取到路由中的课程id值
      const courseId = this.$route.params.id;
      if (courseId) {
        this.courseId = courseId;
        this.getCourseInfo();
      } else {
        this.initData();
      }
    },
    //初始化data;
    initData() {
      Object.assign(this.$data, this.$options.data());
    },
    //下一步
    next() {
      //判断当前是添加还是修改
      if (!this.courseInfo.id) {
        this.addCourseInfo(this.courseInfo);
      } else {
        this.updateCourseInfo()
      }
    },
    //添加课程信息
    addCourseInfo(courseInfo) {
      addCourseInfo(courseInfo).then(res => {
        this.$message({
          type: 'success',
          message: '添加课程信息成功'
        })
        this.$router.push('/course/chapter/' + res.data.courseId)
      }).catch(err => {
      });
    },
    //修改课程信息
    updateCourseInfo() {
      //值发生变化时，才进行修改
      if (this.isUpdate) {
        updateCourseInfo(this.courseInfo).then(res => {
          this.$message({
            type: 'success',
            message: '修改课程信息成功'
          })
          this.$router.push('/course/chapter/' + this.courseInfo.id)
        }).catch(err => {
        });
      }else {
        this.$router.push('/course/chapter/' + this.courseInfo.id)
      }
    },
    //表单验证
    validateForm() {
      if (this.courseInfo.title === "") {
        this.$message({
          type: 'error',
          message: '课程标题不能为空'
        })
        return false;
      }
      return true;
    },
    //获取所有讲师信息
    getAllTeacher() {
      getAllTeacher().then(ser => {
        this.teacherList = ser.data.teachers;
      });
    },
    //查询课程分类树
    getAllSubjectToTree() {
      getAllSubjectToTree().then(res => {
        this.subjectTreeList = res.data.subjectTreeVoList;
      })
    },
    //上传封面成功调用的方法
    handleAvatarSuccess(res, file) {
      this.courseInfo.cover = res.data.url
    },
    //上传之前调用的方法
    beforeAvatarUpload(file) {
      //设置文件格式和大小
      //const isJPG = file.type === 'image/jpeg'
      const isJPG = ['image/png', 'image/jpg', 'image/jpeg'].includes(file.type);
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG、PNG、jpeg 三种格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    //一级类型改变时，清空该商品二级分类
    changeSubjectParentId() {
      this.courseInfo.subjectId = '';
    },
    //获取课程信息（根据id）
    getCourseInfo() {
      getCourseInfo(this.courseId).then(ser => {
        this.courseInfo = ser.data.courseInfo;
      });
    },
  }
}
</script>

<style scoped>
.tinymce-container {
  line-height: 29px;
}
</style>
